package com.blockmeta.bbs.minemodule.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import androidx.core.widget.NestedScrollView;
import android.util.AttributeSet;
import com.blankj.utilcode.util.LogUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;

import com.blockmeta.bbs.minemodule.R;


/**
 * @author AirThor
 * @date 2018/10/18.
 */
public class GuaGuaKa extends View {

    /**
     * 绘制线条的Paint,即用户手指绘制Path
     */
    private Paint mFingerPaint = new Paint();
    /**
     * 记录用户绘制的Path
     */
    private Path mFingerPath = new Path();
    /**
     * 内存中创建的Canvas
     */
    private Canvas mCanvas;
    /**
     * mCanvas绘制内容在其上
     */
    private Bitmap mBitmap;
    /**
     * 是否刮奖完成
     */
    private boolean isComplete;
    /**
     * 覆盖层的Paint
     */
    private Paint mForegroundPaint = new Paint();
    /**
     * 前景图形
     */
    private Rect mTextBound = new Rect();

    private String mText = "￥500,0000";
    /**
     * 手指触摸位置
     */
    private int mLastX;
    private int mLastY;

    /**
     * 是否可以开始刮奖
     */
    private boolean isCanLotteryDraw = false;
    public GuaGuaKa(Context context) {
        this(context, null);
    }

    public GuaGuaKa(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GuaGuaKa(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        mFingerPath = new Path();
        mForegroundPaint = setForegroundPint();
        mFingerPaint = setFingerPaint();
    }

    /**
     * 初始化canvas的绘制用的画笔
     */
    private Paint setForegroundPint() {
        Paint paint = new Paint();
        paint.setStyle(Style.FILL);
        paint.setTextScaleX(2f);
        paint.setColor(Color.DKGRAY);
        paint.setTextSize(32);
        paint.getTextBounds(mText, 0, mText.length(), mTextBound);
        return paint;
    }

    /**
     * 设置画笔的一些参数
     */
    private Paint setFingerPaint() {
        Paint paint = new Paint();
        // 设置画笔
        paint.setColor(Color.parseColor("#c0c0c0"));
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Style.STROKE);
        // 圆角
        paint.setStrokeJoin(Paint.Join.ROUND);
        // 圆角
        paint.setStrokeCap(Paint.Cap.ROUND);
        // 设置画笔宽度
        paint.setStrokeWidth(30);
        return paint;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!isComplete) {
            drawPath();
            canvas.drawBitmap(mBitmap, 0, 0, null);
        }else {
            setVisibility(GONE);
        }
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        resetMask();

    }

    private void resetMask() {
        int w = getMeasuredWidth(); int h = getMeasuredHeight();
        // 初始化bitmap
        mBitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);

        // 绘制遮盖层
        mFingerPaint.setStyle(Style.FILL);
        mCanvas.drawBitmap(BitmapFactory.decodeResource(getResources(),
                R.drawable.bg_guaguaka), null, new RectF(0, 0, w, h), null);
    }

    /**
     * 绘制线条
     */
    private void drawPath() {
        mFingerPaint.setStyle(Style.STROKE);
        mFingerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
        mCanvas.drawPath(mFingerPath, mFingerPaint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!isCanLotteryDraw) {
            return super.onTouchEvent(event);
        }
        ViewParent parent = getParent();
        while (! (parent instanceof NestedScrollView)){
            parent = parent.getParent();
        }

        int action = event.getAction();
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                parent.requestDisallowInterceptTouchEvent(true);
                mLastX = x;
                mLastY = y;
                mFingerPath.moveTo(mLastX, mLastY);
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = Math.abs(x - mLastX);
                int dy = Math.abs(y - mLastY);

                if (dx > 3 || dy > 3) {
                    mFingerPath.lineTo(x, y);
                }
                mLastX = x;
                mLastY = y;
                break;
            case MotionEvent.ACTION_UP:
                parent.requestDisallowInterceptTouchEvent(false);
                new Thread(mRunnable).start();
                break;
            default:
                break;
        }

        invalidate();
        return true;
    }

    /**
     * 统计擦除区域任务
     */
    private Runnable mRunnable = new Runnable() {
        private int[] mPixels;

        @Override
        public void run() {

            int w = getWidth();
            int h = getHeight();

            float wipeArea = 0;
            float totalArea = w * h;

            Bitmap bitmap = mBitmap;

            mPixels = new int[w * h];

            /**
             * 拿到所有的像素信息
             */
            bitmap.getPixels(mPixels, 0, w, 0, 0, w, h);

            /**
             * 遍历统计擦除的区域
             */
            for (int i = 0; i < w; i++) {
                for (int j = 0; j < h; j++) {
                    int index = i + j * w;
                    if (mPixels[index] == 0) {
                        wipeArea++;
                    }
                }
            }

            /**
             * 根据所占百分比，进行一些操作
             */
            if (wipeArea > 0 && totalArea > 0) {
                int percent = (int) (wipeArea * 100 / totalArea);
                LogUtils.e("TAG", percent + "");
                if (percent > 40) {
                    isComplete = true;
                    postInvalidate();
                }
            }
        }

    };

    /**
     * 设置是否可以刮奖
     */
    public void setCanLotteryDraw(boolean canLotteryDraw) {
        isCanLotteryDraw = canLotteryDraw;
    }

    /**
     * 刮奖重置
     */
    public void reset(){
        isComplete = false;
        resetMask();
        mFingerPath.reset();
        postInvalidate();
        setVisibility(VISIBLE);
        //setVisibility(VISIBLE);
    }
}
